-module('guess-key').
-export([eM/1]).

%for 1 <= i <= m
%get the frequencies of the string yi

%% eMs(String, M) ->
%%     ProbabilityDistrubution = probability_distribution(String),
%%     eMs_helper(M, ProbabilityDistrubution, []).
%% eMs_helper(0, ProbabilityDistrubution, EMs) ->
%%     [eM(0,ProbabilityDistrubution)|EMs] ;
%% eMs_helper(M, ProbabilityDistrubution, EMs) ->
%%     eMs_helper(M-1, ProbabilityDistrubution, [eM(G,ProbabilityDistrubution)|EMs]).

eM(String) -> 
    ProbabilityDistrubution = probability_distribution(String),
    eM_helper(ProbabilityDistrubution, 25, []).

eM_helper(ProbabilityDistribution, 0, MgsSoFar) ->
    [computeMg(ProbabilityDistribution, 0)|MgsSoFar] ;
eM_helper(ProbabilityDistribution, G, MgsSoFar) ->
    eM_helper(ProbabilityDistribution, G-1, [computeMg(ProbabilityDistribution, G)|MgsSoFar]).
c
computeMg(ProbabilityDistrubution, G) ->
    computeMg_helper(ProbabilityDistrubution, G, 0, 0).

computeMg_helper(ProbabilityDistribution, G, 25, SumSoFar) ->
    J = (25 + G) rem 26,  
    EP = english:probability(25 + $A),
    P = lists:nth(J + 1, ProbabilityDistribution),
    M = P * EP,
    SumSoFar + M ;
computeMg_helper(ProbabilityDistribution, G, I, SumSoFar) ->
    J = (I + G) rem 26,  
    EP = english:probability(I + $A),
    P = lists:nth(J + 1, ProbabilityDistribution),
    M = P * EP,
    computeMg_helper(ProbabilityDistribution, G, I + 1, SumSoFar + M).

probability_distribution(String) ->
    N = length(String),
    Frequencies = frequencies:frequencies(String),
    probability_distribution_hlpr(Frequencies, N).

probability_distribution_hlpr([], _N) -> 
    [] ;
probability_distribution_hlpr([H|T], N) ->
    [H/N | probability_distribution_hlpr(T,N)].
    
    
    
